package com.example.administrator.myview.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.administrator.myview.BuildConfig;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 网络通信类
 * @author 许润华
 *
 */
public class MyHttpThread extends Thread{
	private Handler handle = null;							//message
	private Context mContext = null;						//调用者句柄
	private String strWaitHint = "";						//等待提示信息

	private String sServerHost = "";						//服务器地址
	private String methodName = null;						//函数名称
	private String params = null;							//参数

	//private DialogCustomProgress progressDialog = null;		//等待对话框
	
	/**
	 * 初始化
	 * @param handler	回调的线程
	 */
	public MyHttpThread(Handler handler){
		handle = handler;
	}

	/**
	 * 线程开始 - 带等待提示信息
	 * @param context		调用窗体句柄	
	 * @param bShowWaiting	是否显示等待对话框，true：显示；false：不显示；
	 * @param sServerHost	服务器地址
	 * @param methodName	方法名
	 * @param params		参数（JSON格式字符串）
	 * @param sWaitHint		等待提示的字符串
	 */
	void doStart(Context context, boolean bShowWaiting, String sServerHost, String methodName, String params, String sWaitHint) {
		strWaitHint = sWaitHint;
		doStart(context, bShowWaiting, sServerHost, methodName, params);
	}
	
	/**
	 * 启动线程
	 * @param context		调用窗体句柄			
	 * @param bShowWaiting	是否显示等待对话框，true：显示；false：不显示；
	 * @param sServerHost	服务器地址
	 * @param methodName	方法名
	 * @param params		参数（JSON格式字符串）
	 */
	public void doStart(Context context, boolean bShowWaiting, String sServerHost, String methodName, String params) {
	    
		// 把参数传进来
		this.mContext = context;
		this.sServerHost = sServerHost;
	    this.methodName = methodName;
	    this.params = params;
	    
	    // 告诉使用者，请求开始了
//	    if (bShowWaiting) {
//			if (progressDialog == null){
//				progressDialog = DialogCustomProgress.createDialog(context);
//			}
//			progressDialog.setCanceledOnTouchOutside(false);	//禁止点击其他地方取消等待提示
//			progressDialog.setTitile(strWaitHint);		//设置等待提示信息
//	    	progressDialog.show();
//	    }
	    
	    // 线程开始了
	    this.start(); 
	}
	
	/**
	 * 线程事件主体
	 */
	@SuppressLint("DefaultLocale")
    @Override
	public void run() {
		super.run();

	    String response;
	    int iFlag = 1;
		
	    //记录输入参数
		long tmRun = new Date().getTime();
		String strLog = "接口："+sServerHost+"?cmd="+methodName+" 参数："+params;
	    Log.d("HttpThread", strLog);
    	writeLogToCard(strLog);	//记录接口日志到文件中

		//判断调试模式&网络状况	
		if (BuildConfig.DEBUG&&false) {	//调试模式&&无网络 进入 离线工作模式
			MyUtils.delay(250);	//延时
	    	response = MyUtils.readCardFile("appSd路径"+methodName+".json");
	    	if (response.length()<=0) response =  "{\"status\":\"1\",\"statusMsg\":\"\",\"returnData\":\"\"}";
		}
		else if (	//实际环境 && 没有调试好的接口，强制用离线数据
				methodName.equals("")							//空

				){	
			MyUtils.delay(500);	//延时
			response = MyUtils.readCardFile("appSd路径"+methodName+".json");
		} else if (	//强制成功
				methodName.equals("")							//空
				
				){
			MyUtils.delay(500);	//延时
			response = "{\"status\": \"1\",\"statusMsg\": \"\",\"returnData\": \"\"}";
		} else {	//实际工作 or 网络连接进入
		    try{
		    	//打包参数
		    	StringEntity se = new StringEntity(params, "UTF-8");	//强制UTF8，防止中文乱码
	
		    	//提交数据
		    	HttpClient httpclient = new DefaultHttpClient();
		    	HttpPost httpPost = new HttpPost(sServerHost+"?cmd="+methodName);
		    	httpPost.setEntity(se);
		    	httpPost.setHeader("Content-type", "application/json");
		    	httpPost.addHeader("Accept-Encoding", "gzip");		//使用addHeader，否则没有效果
		    	httpPost.addHeader("charset", "UTF-8");	//强制UTF8，防止中文乱码
		    	httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
		    	httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 15000);
		    	HttpResponse httpResponse = httpclient.execute(httpPost);
		    	if (httpResponse.getStatusLine().getStatusCode() == 200) {  //服务器返回数据
		    		Header header = httpResponse.getFirstHeader("Content-Encoding");  
		    		if (header != null && header.getValue().contains("gzip")) {	//首先判断服务器是否支持gzip压缩  
		    			InputStream is = new BufferedInputStream(httpResponse.getEntity().getContent());  
		    			response = MyUtils.readDataForZgip(is, "UTF-8");
		    		}
		    		else {	//不压缩方式数据
		    			response = EntityUtils.toString(httpResponse.getEntity());	      
		    		}

		    		//保存分类数据
		    		if (response.length()>0 && methodName.equals("getCategoryData")) {
		    			MyUtils.writeFile(mContext, methodName+".json", response);
		    		}
		    	}
		    	else {  //服务器返回不正确
		    	    Log.d("HttpThread", "错误状态码："+ httpResponse.getStatusLine().getStatusCode());
		    		iFlag = 2;
		    		response = httpResponse.getStatusLine().toString();  
		    	}
	    	} catch (Exception e) {
		    	iFlag = 2;
		    	response = e.toString();
				e.printStackTrace();
			}
	    }

	    //记录输出参数
		tmRun = new Date().getTime() - tmRun;
		strLog = String.format("返回(%s执行%.3f秒)：", methodName, (tmRun*1.0f)/1000)+response;
	    Log.d("HttpThread", strLog);
    	writeLogToCard(strLog);	//记录接口日志到文件中
			
	    //构造消息,发送数据到主进程
        Message message=handle.obtainMessage();
        Bundle b=new Bundle();
        message.what = iFlag; 	//服务器返回值
        b.putString("data", response.trim()); //这里是消息传送的数据
        message.setData(b);
        handle.sendMessage(message);	    	

	    //取消进度对话框
//	    if (progressDialog != null) {
//	    	progressDialog.dismiss();
//	    	progressDialog = null;
//	    }
	}

	//接口日志保存到卡中文件（测试版本才记录）
	@SuppressLint("SimpleDateFormat")
    private void writeLogToCard(String message) {
	    if ((!sServerHost.equals("https://app.2298.com/api/2298/api.aspx") &&
				!sServerHost.equals("https://pp.2298.com/api/2298/api.aspx")) || BuildConfig.DEBUG) {
			String path = Environment.getExternalStorageDirectory()+"appSd路径"+"log/";
			File dirLog = new File(path);
			if(!dirLog.exists()) dirLog.mkdirs();	//没有目录就创建
		    SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMdd");
		    //public static final String APP_SD_PATH 		= "/2298/";	例子							//SD卡缓存路径
			String fileName = Environment.getExternalStorageDirectory()+"appSd路径"+"log/log"+sDateFormat.format(new Date())+".txt";
			File fileLog = new File(fileName);
			sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			message = sDateFormat.format(new Date())+" "+message+"\r\n";
	        try {  
	    		if (fileLog.exists()) {	//存在打开，往后添加
	                FileWriter writer = new FileWriter(fileName, true);  
	                writer.write(message);  
	                writer.close();  
	    		} else {	//不存在，新建文件；
	                FileWriter writer = new FileWriter(fileName);  
	                writer.write(message);  
	                writer.close();  
	    		}
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }   
	    }
	}


	
}
